from apps.system.lessee.baseViews import *
from apps.system.user.dao import UserDao, UserModelSerializer
from apps.account.serializers import Token
from apps.system.lessee.functions import onekeyLessee
from apps.merchant.shop.dao import ShopDao

class LesseeForPViewSet(BaseLesseeViewSet):
    authentication_classes = []
    permission_classes = []

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = LesseeDao().findAllLessee()
        return _list

    @action(methods=['post'], detail=False)
    def lesseeData(self, request):
        params = getRequestParams(request)
        lessee = LesseeDao().getLessee()
        # 商户数
        shopCount = ShopDao().findAll().filter(checkStatus='PASS').count()
        return Response(response_success({
            'shopCount': shopCount
        }))

class LesseeViewSet(BaseLesseeViewSet):

    def get_queryset(self):
        params = getRequestParams(self.request)
        _list = LesseeDao().findAllLessee()
        return _list

    '''切换商户'''
    @action(methods=['post'], detail=False)
    def changeLessee(self, request):
        params = getRequestParams(request)
        if not params.get('lesseeId'):
            return Response(response_message(('lesseeId参数必填')))
        _lesseeId = params.get('lesseeId')
        _admin = UserDao().findAll().filter(lessee__id=_lesseeId, role='lessee').first()
        print('_admin', _admin)
        tokens = Token.objects.filter(user=_admin)
        print('tokens', tokens)
        token = None
        if tokens.count() > 0:
            token = tokens.first()
        else:
            token = Token.objects.create(user_id=_admin.id)
        print('token', token)
        userData = UserModelSerializer(token.user).data
        return Response(response_success({'key': token.key, 'userModel': userData}))

    '''一键开店'''
    @action(methods=['post'], detail=False)
    def onekeyLesseeAction(self, request):
        params = getRequestParams(request)
        try:
            onekeyLessee(params, request)
        except VerifyException as e:
            return Response(response_message(e.message))
        return Response(response_success("操作成功"))

